<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="organizationRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    :closable="false"
    title="授权"
    showFooter
    isDetail
  >
    <div class="box-drawer">
      <div class="drawer-name">{{ drawerInfo.record.orgName }}</div>
      <div class="drawer-box">
        <div class="box-title">产品权限</div>
        <div class="content-auth" v-loading="loading">
          <div class="auth-left auth-box">
            <div class="box-name">请选择产品权限</div>
            <a-tabs v-model:activeKey="activeKey" tab-position="left" animated>
              <a-tab-pane v-for="item in drawerInfo.allArr" :key="item.appId" :tab="item.appName">
                <div class="left-item" v-for="items in item.items" :key="items.authId">
                  <div class="item-check">
                    <a-checkbox
                      v-model:checked="items.checked"
                      :disabled="items.disabled"
                      @change="(e:any)=>{checkChange(e,items)}"
                      >{{ items.authName }}</a-checkbox
                    >
                  </div>
                  <div class="item-time" v-show="items.checked">
                    <a-range-picker
                      v-model:value="items.timeRange"
                      :allowClear="false"
                      valueFormat="YYYY-MM-DD"
                      :disabled-date="disabledDate"
                    />
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
          <div class="auth-right auth-box">
            <div class="box-name">已选择产品权限</div>
            <template v-for="item in drawerInfo.allArr" :key="item.appId">
              <div class="list-production" v-if="subChildExit(item)">
                <div class="production-title">
                  {{ item.appName }}
                </div>
                <template v-for="items in item.items" :key="items.authId">
                  <div class="production-list" v-if="items.checked">
                    <div class="list-title">{{ items.authName }}</div>
                    <div class="list-time">
                      <template v-if="items.timeRange && items.timeRange.length">
                        {{ items.timeRange[0] }} 至 {{ items.timeRange[1] }}
                      </template>
                    </div>
                    <div class="list-close" @click="items.checked = false" v-if="!items.disabled">
                      <CloseCircleFilled />
                    </div>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, createVNode } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import Empty from '@/components/Empty/index.vue'
import { CloseCircleFilled } from '@ant-design/icons-vue'
import { setPropAuthList, getCheckAuthList } from '@/utils'
import { authCodeMap } from '@/utils/permissionCodeMap'
import dayjs, { Dayjs } from 'dayjs'
import { cloneDeep } from 'lodash-es'
import { message, Modal } from 'ant-design-vue'
import api from '@/api'

const { appAuthList, enterpriseAuth, enterpriseDetail } = api

const emit = defineEmits(['register', 'backEdit'])

const loading = ref(false)

const activeKey = ref('')

const drawerInfo = reactive<any>({
  record: {},
  allArr: []
})

// 选择当天之后时间
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().startOf('day')
}
const [organizationRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.record = cloneDeep(data.record)
  try {
    loading.value = true
    let authRes = await appAuthList({ orgTenantId: drawerInfo.record?.tenantId })
    drawerInfo.allArr = setPropAuthList(authRes.result)

    let activeKeys = authRes.result[0].appId
    if (drawerInfo.allArr && drawerInfo.allArr.length) {
      for (let i = 0; i < drawerInfo.allArr.length; i++) {
        if (drawerInfo.allArr[i].items.some((item: any) => item.checked)) {
          activeKeys = drawerInfo.allArr[i].appId
          break
        }
      }
    }
    activeKey.value = activeKeys
    let detailRes = await enterpriseDetail({ orgTenantId: drawerInfo.record?.tenantId })
    drawerInfo.record = { ...drawerInfo.record, ...detailRes.result }
    loading.value = false
  } catch (error) {
    loading.value = false
  }
})

const drawerReset = () => {
  drawerInfo.allArr = []
  changeOkLoading(false)
}
const checkChange = (e: any, items: any) => {
  // 销项限制条件
  let record = drawerInfo.record
  if (items.authId === authCodeMap.writeOff && e.target.checked) {
    if (record.serviceType === null || record.taxPlateType === null) {
      items.checked = false
      Modal.confirm({
        title: () => '新建该企业时尚未选择服务类型、税盘类型，无法勾选销项，请前往添加',
        okText: () => '前往',
        icon: () => createVNode(CloseCircleFilled, { style: 'color: #C72A2A' }),
        centered: true,
        autoFocusButton: null,
        class: 'modal-confirm-box',
        onOk() {
          closeDrawer()
          emit('backEdit')
        },
        onCancel() {}
      })
    }
  } else if (items.authId === authCodeMap.income && e.target.checked) {
    // 进项限制条件
    if (!record.aceId || !record.aceKey || !record.contactEmail) {
      items.checked = false
      Modal.confirm({
        title: () => '新建该企业时尚未选择联系人邮箱、采集鉴权ID和采集鉴权Key，无法勾选进项，请前往添加',
        okText: () => '前往',
        icon: () => createVNode(CloseCircleFilled, { style: 'color: #C72A2A' }),
        centered: true,
        autoFocusButton: null,
        class: 'modal-confirm-box',
        onOk() {
          closeDrawer()
          emit('backEdit')
        },
        onCancel() {}
      })
    }
  } else if (items.authId === authCodeMap.interfaceOn && e.target.checked) {
    // 接口开放平台限制条件
    if (!(record.bankAccount && record.bankName && record.address && record.cellTel)) {
      items.checked = false
      Modal.confirm({
        title: () => '新建该企业时尚未选择银行账号、开户银行、注册地址、注册电话，无法勾选进项，请前往添加',
        okText: () => '前往',
        icon: () => createVNode(CloseCircleFilled, { style: 'color: #C72A2A' }),
        centered: true,
        autoFocusButton: null,
        class: 'modal-confirm-box',
        onOk() {
          closeDrawer()
          emit('backEdit')
        },
        onCancel() {}
      })
    }
  }
}
// 子节点是否存在授权
const subChildExit = (item: any) => {
  if (item.items && item.items.length) {
    return item.items.some((data: any) => data.checked)
  } else {
    return false
  }
}
// 提交数据
const confirmSubmit = async () => {
  let backData: any = getCheckAuthList(drawerInfo.allArr)
  if (!backData.check) {
    let { messageObj } = backData
    return message.warning(`${messageObj.appName}下的${messageObj.authName}时间未选择`)
  }
  if (backData.authList && backData.authList.length === 0) {
    return message.warning('请至少选择一个产品')
  }
  try {
    changeOkLoading(true)
    await enterpriseAuth({
      orgTenantId: drawerInfo.record?.tenantId,
      authList: backData.authList
    })
    message.success('企业授权成功')
    closeDrawer()
    drawerReset()
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.box-drawer {
  position: relative;
  padding: 30px 24px;
  .drawer-name {
    padding-left: 12px;
    padding-bottom: 8px;
    margin-bottom: 24px;
    font-size: 16px;
    font-weight: 600;
    color: @text-color;
    line-height: 22px;
    position: relative;
    border-bottom: 1px solid #e0e1e6;
    &::before {
      content: '';
      width: 4px;
      height: 16px;
      background: @primary-color;
      border-radius: 2px;
      position: absolute;
      left: 0;
      top: 2px;
    }
  }
  .drawer-box {
    padding: 30px 24px 24px;
    border-radius: 2px;
    border: 1px solid #e0e1e6;
    .box-title {
      padding-bottom: 8px;
      margin-bottom: 22px;
      font-size: 16px;
      font-weight: 600;
      color: @text-color;
      border-bottom: 1px solid #e0e1e6;
    }
    .content-auth {
      min-height: 420px;
      position: relative;
      display: flex;
      justify-content: space-between;
      .auth-left {
        width: 58%;
        :deep(.ant-tabs) {
          height: 100%;
          .ant-tabs-nav {
            min-width: 200px;
            .ant-tabs-tab {
              font-size: 12px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 500;
              height: 42px;
              line-height: 42px;
              margin: 0;
              border-bottom: 1px solid #e8e8e8;
            }
            .ant-tabs-ink-bar {
              display: none;
            }
            .ant-tabs-tab-active {
              position: relative;
              &::after {
                content: '';
                width: 6px;
                height: 42px;
                border-radius: 2px;
                background-color: #fff;
                position: absolute;
                right: -4px;
                top: 0;
              }
            }
          }
          @media (max-width: 1300px) {
            .ant-tabs-nav {
              min-width: 140px;
            }
          }
        }
        .left-item {
          min-height: 52px;
          padding: 4px 10px 4px 0;
          display: flex;
          align-items: center;
          &:first-child {
            padding-top: 10px;
          }
          .item-check {
            min-width: 140px;
            :deep(.ant-checkbox) + span {
              padding-left: 35px;
            }
          }
        }
      }
      .auth-right {
        width: 40%;
        .list-production {
          color: #192236;
          font-size: 12px;
          font-weight: 600;
          .production-title {
            padding: 10px 0 10px 16px;
            border-top: 1px solid #e8e8e8;
            border-bottom: 1px solid #e8e8e8;
          }
          &:first-child .production-title {
            border-top: none;
          }
          .production-list {
            min-height: 42px;
            padding-left: 16px;
            display: flex;
            align-items: center;
            .list-title {
              min-width: 80px;
            }
            .list-time {
              min-width: 145px;
              margin-left: 10px;
              margin-right: 15px;
            }
            .list-close {
              color: #c0c0c0;
              font-size: 14px;
              cursor: pointer;
            }
          }
        }
      }
      .auth-box {
        border: 1px solid #e0e1e6;
        .box-name {
          height: 44px;
          line-height: 44px;
          font-size: 16px;
          font-weight: 600;
          padding-left: 16px;
          color: #172237;
          background: #fafafa;
          border-bottom: 1px solid #e0e1e6;
        }
      }
    }
  }
}
</style>
